<?php
/**
 * ***********************************************************************************
 * 咨询鲤 PC端知识店铺-搜索商品
 * 
 * @author Mr.RJH
 * @date 2025-09-16
 * @email<15213026209@163.com>
 * ***********************************************************************************
 */
namespace app\controller;

use app\BaseController;

use app\model\product\ZxlKnowStoreProductModel;

use app\service\ProductService;

class Search extends BaseController
{
    /**
     * 搜索页
     * 
     * @return mixed
     */
    public function index()
    {
        $productService = new ProductService($this->request->m_id);
        // 随机推荐
        $list = $productService->rand_recommend_product(18);

        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 搜索结果页
     * 
     * @return mixed
     */
    public function result()
    {
        if ($this->request->isPost()) {
            $limit = $this->request->param('limit', 10);
            $page = $this->request->param('page',1);
            $keywords = $this->request->param('keywords', '');
            $m_id = $this->request->m_id;
            try {
                //查询条件
                $where = function($q)use($m_id, $keywords){
                    $q->where('m_id', $m_id);
                    $q->where('is_delete', 0);
                    $q->where('status', 1);
                    $q->whereIn('product_type', ZxlKnowStoreProductModel::PC_PRODUCTTYPE);
                    $q->where('visible_range', 0);
                    if ($keywords != '') {
                        $q->where('name','like','%'.trim($keywords).'%');
                    }
                };
                $query = ZxlKnowStoreProductModel::with("attrMinPrice")->where($where);
                $list = $query->field('id,name,sub_title,product_type,head_imgs,background_color,real_sales,virtual_sales,tags')->order(['sort' => 'desc','create_time' => 'desc'])->paginate($limit,false,['page'=>$page])->toArray();
                foreach ($list['data'] as &$v) {
                    if ($v['product_type'] == 10) {
                        $v['head_imgs'] = '/static/images/exam.png';
                    } else {
                        $v['head_imgs'] = $v['head_imgs'] ? explode(',',$v['head_imgs'])[0] : '/static/images/no_pic_1.png';
                    }
                    $v['product_type_text'] = ZxlKnowStoreProductModel::getPcProductType($v['product_type']);
                    $v['href'] = ZxlKnowStoreProductModel::getPcProductDetailHref($v['product_type'], $v['id']);
                }
                
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }

        $keywords = $this->request->param('keywords');
        
        $this->assign('keywords', $keywords);
        return $this->fetch();
    }
}